package com.citytechinc.cmis.client.service
{
	import com.citytechinc.cmis.client.event.QueryEvent;
	import com.citytechinc.cmis.client.model.Document;
	import com.citytechinc.cmis.client.model.Repository;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	
	import mx.collections.ArrayCollection;

	
	
	public class QueryService extends EventDispatcher
	{
		private namespace app = "http://www.w3.org/2007/app";
		private namespace atom = "http://www.w3.org/2005/Atom";
		private namespace cmis = "http://docs.oasis-open.org/ns/cmis/core/200901";
		
		use namespace app;
        use namespace atom;
        use namespace cmis;
        
		private var auth:String;
		
		public function QueryService(auth:String)
		{
			this.auth = auth;
		}
		
		public function getQueryResults(repository:Repository, queryStr:String):void 
		{			
			var query:XML = 
				<cmis:query xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200901" 
						xmlns:p="http://www.w3.org/1999/xhtml" 
						xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
		  			<cmis:statement>{queryStr}</cmis:statement>
		  			<cmis:searchAllVersions>true</cmis:searchAllVersions>
		  			<cmis:pageSize>100</cmis:pageSize>
		  			<cmis:skipCount>0</cmis:skipCount>
		  			<cmis:returnAllowableActions>false</cmis:returnAllowableActions>
				</cmis:query>;
			
			var request:URLRequest = new URLRequest(repository.queryURL);

			request.data = query;

			
			request.contentType = "application/cmisquery+xml";
			request.method = URLRequestMethod.POST;
			
			var header:URLRequestHeader;

            header = new URLRequestHeader("Authorization", "Basic " + auth);
            
            request.requestHeaders.push(header);

			var loader:URLLoader = new URLLoader();

			loader.addEventListener(Event.COMPLETE, setQueryResults);
			
            loader.addEventListener ( IOErrorEvent.IO_ERROR, handleIOError );
            loader.addEventListener ( HTTPStatusEvent.HTTP_STATUS, handleHttpStatus );
            loader.addEventListener ( SecurityErrorEvent.SECURITY_ERROR, handleSecurityError );
            loader.addEventListener ( Event.COMPLETE, handleComplete );
 
			loader.load(request); 
		}
		
        private function handleIOError ( event:IOErrorEvent ):void
        {
            trace ( "Load failed: IO error: " + event.text );
        }
        private function handleHttpStatus ( event:HTTPStatusEvent ):void
        {
            trace ( "Load failed: HTTP Status = " + event.status );
        }
        private function handleSecurityError ( event:SecurityErrorEvent ):void
        {
            trace ( "Load failed: Security Error: " + event.text );
        }
        private function handleComplete ( event:Event ):void
        {
            trace ( "The data has successfully loaded" );
        }
		
		
		private function setQueryResults(event:Event):void 
		{
			var results:ArrayCollection = new ArrayCollection();
			
			var loader:URLLoader = URLLoader(event.target);

			var resultXML:XML = new XML(loader.data);
			
			for each (var d:XML in resultXML.entry)
				results.addItem(Document.getDocument(d));
				
			this.dispatchEvent(new QueryEvent(QueryEvent.RESULTS, results));
		}

	}
	
}